package com.wisdom.benefit.jufa.my;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wisdom.benefit.jufa.R;
import com.wisdom.benefit.jufa.base.BaseActivity;
import com.wisdom.benefit.jufa.net.RetrofitService;
import com.wisdom.benefit.jufa.utils.CommonUtils;
import com.wisdom.benefit.jufa.utils.DataCleanManager;
import com.wisdom.benefit.jufa.utils.DialogUtil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class NewCollectionCodeActivity extends BaseActivity {
    private Button btn, addBtn, finishBtn;
    private EditText nameEt, zfbNameEt, zfbAccountEt;
    private Dialog dialog;
    private View inflate;
    private static final int PHOTO_REQUEST = 1;
    private static final int CAMERA_REQUEST = 2;
    private TextView camera;
    private TextView pic;
    private TextView cancel;
    private String basePic, qrCodeRealName, payAccountPassword;
    private Long userIdCreate, belongPassageway;
    private int PassagewayType;
    private LinearLayout zfbNameLl, zfbAccountLl;

    @Override
    protected int getLayout() {
        return R.layout.activity_new_collection_ode;
    }

    @Override
    protected void initViews() {
        //上传二维码
        btn = findViewById(R.id.new_collection_code_btn);
        //支付宝真是姓名
        zfbNameLl = findViewById(R.id.new_collection_code_zfb_name_ll);
        zfbNameEt = findViewById(R.id.new_collection_code_zfb_name);
        //支付宝账号或吱口令
        zfbAccountLl = findViewById(R.id.new_collection_code_zfb_account_ll);
        zfbAccountEt = findViewById(R.id.new_collection_code_zfb_account);
        //收款名
        nameEt = findViewById(R.id.new_collection_code_name);
        //确实
        addBtn = findViewById(R.id.new_collection_code_add_btn);
        //取消
        finishBtn = findViewById(R.id.new_collection_code_cancel_btn);
        belongPassageway = getIntent().getLongExtra("PassagewayId", 0);
        userIdCreate = getIntent().getLongExtra("userId", 0);
        PassagewayType = getIntent().getIntExtra("PassagewayType", 4);
        if (PassagewayType == 4) {
            zfbNameLl.setVisibility(View.VISIBLE);
            zfbAccountLl.setVisibility(View.VISIBLE);
        }
        if (PassagewayType == 4) {
            btn.setVisibility(View.GONE);
        }
        setClick();
    }

    /**
     * 设置监听
     *
     * @return
     */
    private void setClick() {
        //上传二维码
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show();
            }
        });
        //取消
        finishBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //确实
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PassagewayType == 4) {
                    if (nameEt.getText().toString().equals("")) {
                        Toast.makeText(NewCollectionCodeActivity.this, "请填写收款名", Toast.LENGTH_SHORT).show();

                    } else if (zfbNameEt.getText().toString().equals("")) {
                        Toast.makeText(NewCollectionCodeActivity.this, "请填写支付宝真实姓名", Toast.LENGTH_SHORT).show();

                    } else if (zfbAccountEt.getText().toString().equals("")) {
                        Toast.makeText(NewCollectionCodeActivity.this, "请填写支付宝账号或吱口令", Toast.LENGTH_SHORT).show();

                    } else {
                        startDialog();

                    }
                } else {
                    if (nameEt.getText().toString().equals("")) {
                        Toast.makeText(NewCollectionCodeActivity.this, "请填写收款名", Toast.LENGTH_SHORT).show();

                    } else if (TextUtils.isEmpty(basePic)) {
                        Toast.makeText(NewCollectionCodeActivity.this, "请上传收款二维码", Toast.LENGTH_SHORT).show();

                    } else {
                        paymentCodeSave(userIdCreate, PassagewayType, nameEt.getText().toString(), "", basePic, belongPassageway, "", "");
                    }
                }
            }
        });
    }

    /**
     * 切换通道(打开)
     */
    private void startDialog() {
        DialogUtil dialogUtil = new DialogUtil(getActivity(), getActivity());
        dialogUtil.dialog("提示", "所填资料是否真实？", "取消", "确定", "1");
        dialogUtil.setOnItemClickListener(new DialogUtil.OnItemClickListener() {
            @Override
            public void onItemCancelClick() {
                Log.d("onItemClick", "你点击了取消");
            }

            @Override
            public void onItemConfirmClick() {


            }

            @Override
            public void onItemValueConfirmClick(String a) {
                boolean b = DataCleanManager.clearAllCache(getActivity());
                if (b == true) {
                    if (PassagewayType == 4) {
                        paymentCodeSave(userIdCreate, PassagewayType, nameEt.getText().toString(), "", zfbAccountEt.getText().toString(), belongPassageway, zfbNameEt.getText().toString(), zfbAccountEt.getText().toString());
                    } else {
                        paymentCodeSave(userIdCreate, PassagewayType, nameEt.getText().toString(), "", basePic, belongPassageway, zfbNameEt.getText().toString(), zfbAccountEt.getText().toString());
                    }

                }
            }
        });
    }


    @Override
    protected int getTitleStringRes() {
        return 0;
    }

    public void show() {
        dialog = new Dialog(getActivity(), R.style.DialogTheme);
        //填充对话框的布局
        inflate = LayoutInflater.from(getActivity()).inflate(R.layout.photo_other_dialog_item, null);
        //初始化控件
        camera = (TextView) inflate.findViewById(R.id.camera);
        pic = (TextView) inflate.findViewById(R.id.pic);
        cancel = (TextView) inflate.findViewById(R.id.cancel);
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否有相机权限
                if (ContextCompat.checkSelfPermission(NewCollectionCodeActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(NewCollectionCodeActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                } else {
                    getCamera();
                    dialog.dismiss();
                }

            }
        });
        pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPhoto();
                dialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        //将布局设置给Dialog
        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
//       将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialog.show();//显示对话框
    }

    /**
     * 从系统相机选择图片来源
     */
    private void getCamera() {
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, CAMERA_REQUEST);
    }

    /**
     * 从相册选择图片来源
     */
    private void getPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, PHOTO_REQUEST);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_REQUEST:
                switch (resultCode) {
                    case -1://-1表示拍照成功
                        Bundle bundle = data.getExtras();
                        Bitmap bitmap = (Bitmap) bundle.get("data");
//                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//
//                        Matrix matrix = new Matrix();
//
//                        matrix.setScale(0.5f, 0.5f);
//
//                        Bitmap bm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
//
//                                bitmap.getHeight(), matrix, true);
//                        Log.i("wechat", "压缩后图片的大小" + (bm.getByteCount() / 1024 / 1024)
                        Bitmap bm = compressImage(bitmap);
//                                + "M宽度为" + bm.getWidth() + "高度为" + bm.getHeight());
                        basePic = bitmapToBase64(bm);
//                        byte[] decodedString = Base64.decode(a, Base64.DEFAULT);
//                        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                        break;
                }
                break;

            case PHOTO_REQUEST://从相册取
                if (data != null) {
                    Uri uri = data.getData();
                    try {
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
                        basePic = bitmapToBase64(bitmap);
//                        byte[] decodedString = Base64.decode(a, Base64.DEFAULT);
//                        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
                break;
        }
    }

    /*
     * bitmap转base64
     * */
    private static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    /**
     * 新增收款码
     */
    private void paymentCodeSave(Long userIdCreate, int passagewayId, String payeeName, String accountNumber, String qrCode, Long belongPassageway, String qrCodeRealName, String payAccountPassword) {
        showProgressDialog("正在新增收款码");
        addDisposable(RetrofitService.getNetService()
                .paymentCodeSave((long) userIdCreate, passagewayId, payeeName, accountNumber, 0, qrCode, "", belongPassageway, qrCodeRealName, payAccountPassword)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getCode() == 0) {
                        showBindToast("新增收款码成功");
                        finish();
                    } else {
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("新增失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }

    /**
     * 质量压缩方法
     *
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length / 1024 > 500) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

}
